import random,os
import string
import datetime
import json
from django.shortcuts import render,get_object_or_404
from django.views.generic import TemplateView, ListView
from django.http import HttpResponse, HttpResponsePermanentRedirect
from django.views.generic.edit import FormView
from django.http import StreamingHttpResponse
from .models import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from pure_pagination.mixins import PaginationMixin
from django.views.generic import DetailView, ListView
from atl.forms import *
from django.utils.encoding import escape_uri_path


# Create your views here.
def Homeview (request):
    # return HttpResponse ('hello')
    return render (request,'base.html')
    

def show_all (request):
    content = Atl.objects.all().order_by ('nums')
    return render (request,'atl/content.html',{'content':content})
    
def search (request):
    q = request.GET.get ('kw')
    if not q:
        error_msg = "请输入搜索软件名称"
        messages.add_message (request,messages.ERROR,error_msg,extra_tags = 'danger')
        return redirect ('atl:show_all')
    
    content = Atl.objects.filter (name__icontains = q)
    return render (request,'atl/content.html',{'content':content})
    
def category(request,pk):
    cate = get_object_or_404 (Category,pk=pk)
    p = cate.atl_set.all().order_by ('nums')
    paginator = Paginator (p,10)
    
    page = request.GET.get ('page')
    
    try:
        content = paginator.page (page)
    except PageNotAnInteger:
        # 如果用户请求的页码号不是整数，显示第一页
        content = paginator.page (1)
    except EmptyPage:
        # 如果用户请求的页码号超过了最大页码号，显示最后一页
        content = paginator.page (paginator.num_pages)
    
    return render (request,'atl/content.html',{'content':content})
    
class IndexView(PaginationMixin, ListView):
    model = Atl
    template_name = "atl/content.html"
    context_object_name = "content"
    paginate_by = 10
    
def pages (request):
    p = Atl.objects.all().order_by ('nums')
    paginator = Paginator (p,10)
    
    page = request.GET.get ('page')
    try:
        content = paginator.page (page)
    except PageNotAnInteger:
        # 如果用户请求的页码号不是整数，显示第一页
        content = paginator.page (1)
    except EmptyPage:
        # 如果用户请求的页码号超过了最大页码号，显示最后一页
        content = paginator.page (paginator.num_pages)  

    return  render (request,'atl/content.html',{'content':content})
    
def download (request,pk):
    # file_path = r'\\172.25.1.189\share\setup.exe'
    # with open (path,'rb') as f:
        # c = f.read() # 这种方式简单粗暴，适合小文件的下载
    # return HttpResponse (c)
    p = get_object_or_404 (Atl,pk = pk)
    file_path = p.down   
        
    if file_path  == '#':
        return HttpResponse ('暂无下载')
    else:
        p.increase_views()
        with open (file_path, 'rb') as f:
            try:
                response = HttpResponse(f)
                response['content_type'] = "application/octet-stream"
                
                response['Content-Disposition'] = 'attachment;filename="{0}"'.format(escape_uri_path(os.path.basename(file_path)))
                
                return response
            except Exception:
                return HttpResponse ('暂无下载')
            
    # def file_iterator (path,chunk_size = 1024):
        # with open (file_path) as f:
            # while True:
                # c = f.read (chunk_size )
                # if c:
                    # yield c 
                # else:
                    # break
    # file = 'setup.exe'
    # response = StreamingHttpResponse (file_iterator(file_path))
    
    # response['Content-Type'] = 'application/octet-stream'
    # response['Content-Disposition'] = 'attachment;filename="{}"'.format(file)
    # 通过文件流传输到浏览器，但文件流通常会以乱码形式显示到浏览器中，而非下载到硬盘上，因此，还要在做点优化，让文件流写入硬盘。
    # return response 
    
def form (request):
    if request.method == 'POST':
        form = UploadForm (request.POST,request.FILES)
        if form.is_valid():
            class_name = form.cleaned_data ['select']
            file = form.cleaned_data ['file']
            
            print (file)
            path = r'\\172.17.25.73\Temp'
            uploadFile (path,file)
            p = Atl (
                class_name = class_name,
                name = file.name,
                link = path,
                down = path+'\\'+file.name,
                )
            p.save()
            
            return HttpResponse ('HeLLO')
    else: # 当正常访问时
        form = UploadForm()
    return render (request,'atl/form.html',{'form':form})
    
def uploadFile (path,file):
    with open (path+"\\{}".format (file.name) ,'wb') as f:
        for chunk in file.chunks():
            f.write (chunk)
        
    
    